package com.app.util.beanutil;

import java.text.SimpleDateFormat;

public class DataConvert {

	private final static String default_str = "" ;
	private final static int default_int = 0 ;
	private final static byte default_byte = 0 ;
	private final static short default_short = 0 ;
	private final static long default_long = 0l ;
	private final static double default_double = 0.00 ;
	private final static float default_float = 0.0f ;
	private final static char default_char = ' ' ;
	private final static boolean default_boolean = false ;
	
	
	private final static SimpleDateFormat format1=new SimpleDateFormat("yyyy-MM-dd");
	private final static SimpleDateFormat format2=new SimpleDateFormat("yyyy-MM-dd HH:mm");
	private final static SimpleDateFormat format3=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	//将数据转化成type类型数据
	public static Object convertToType(Class<?> type,String value){
		
		if(type == null) return null ;
		
		//转string类型
		if(type == java.lang.String.class){   //字符串类�?
			return value ;
		}
		
		//转字节型
		if(type == java.lang.Byte.class || type == byte.class ){   //字节类型
			try{
				return Byte.parseByte(value);
			}catch(Exception e){
				return default_byte ;
			}
		}
		
		//转short
		if(type == java.lang.Short.class || type == short.class ){
			try{
				return Short.parseShort(value);
			}catch(Exception e){
				return default_short ;
			}
			
		}
		
		//转int
		if(type == java.lang.Integer.class || type == int.class ){  //整数类型
			try{
				return Integer.parseInt(value) ;
			}catch(Exception e){
				return default_int ;
			}
		}
		
		//转long
		if(type == java.lang.Long.class || type == long.class ){
			try{
				return Long.parseLong(value);
			}catch(Exception e){
				return default_long ;
			}
		}
		
		//转字�?
		if(type == java.lang.Character.class || type == char.class){
			
			if(value == null) return default_char ;
			return new Character(value.toString().charAt(0));
		}
		
		if(type == java.lang.Double.class || type == double.class){
			try{
				return Double.parseDouble(value);
			}catch(Exception e){
				return default_double;
			}
		}
		
		if(type == java.lang.Float.class || type == float.class){
			try{
				return Float.parseFloat(value) ;
			}catch(Exception e){
				return default_float ;
			}
		}
		if(type == java.lang.Boolean.class || type == boolean.class){
			
			try{
				return Boolean.parseBoolean(value);
			}catch(Exception e){
				return default_boolean ;
			}
		}
		
		if(type == java.util.Date.class){
			if(value == null || value.equals("")){
				return null ;
			}
			try{
				if(value.indexOf(":") == -1 && value.length() == 10){
					return format1.parse(value);
				}else if(value.indexOf(":") > -1 && value.length() == 16){
					return format2.parse(value);
				}else if(value.indexOf(":") > -1 && value.length() == 19){
					return format3.parse(value);
				}
			}catch(Exception e){
				return null;
			}
		}
		
		
		return null;
	}
}
